import { start } from "../common/bootstrap";
import { V } from "x-engine";
import * as zookeeper from "node-zookeeper-client";
import * as util from "util";
import { Buffer } from "buffer";
import { CreateMode } from "node-zookeeper-client";

let config: any = start();
console.log(config);

V.startExpressServer({
    crossDomain: true,
    port: config.service.port,
});


let zk = zookeeper.createClient("localhost:2181");
zk.on("connected", () => {

    (async () => {
        let exists = (path) => {
            return new Promise((resolve, reject) => {
                zk.exists(path, (err, stat) => {
                    if (err) reject();
                    resolve(stat);
                })
            });
        }
        let create = (path, data?, forever?) => {
            return new Promise((resolve, reject) => {
                zk.create(data ? path + '/' + data : path, new Buffer(""), forever ? CreateMode.PERSISTENT : CreateMode.EPHEMERAL, (err, path) => {
                    if (err) reject();
                    console.log(path)
                    resolve();
                });

            });
        };


        try {
            let flag = await exists("/service");
            if (!flag) {
                await create("/service", null, true);
            }
            await create("/service", (config.service.port));

            zk.getChildren("/service", (err, children) => {
                console.log(children);
            })
            // console.log(flag);
        }
        catch (e) {
            console.log(e);
        }

    })();

    // zk.exists("/service",(err,stat) => {
    // zk.create("/service",)
    // });

    console.log("zookeeper connected");
});
zk.connect();



console.log("service is listening port " + config.service.port);